<template>
  <div id="app">
    <!-- todoList -->
    <MyHeader @addTodo="addTodo"/>
    <MyList :todos="todos"/>
    <MyFooter :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"/>
  </div>
</template>

<script>
  import PubSub from 'pubsub-js';
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter'
  export default {
    name: 'App',
    components: {MyHeader,MyList,MyFooter},
    data(){
        return{
            todos:[
                {id:'001',title:'学习',done:true},
                {id:'002',title:'听音乐',done:false},
                {id:'003',title:'写作业',done:true}
            ]
        }
    },
    methods: {
      addTodo(todoObj){
        //console.log('我是app组件，我收到了数据：',todoObj)
        this.todos.unshift(todoObj)
      },
      // 勾选or取消勾选一个todo
      checkTodo(id){
        this.todos.forEach(todo => {
          if(todo.id == id) todo.done = !todo.done
        });
      },
      // 删除一个todo "_"下划线占个位
      deteleTodo(_,id){
        this.todos = this.todos.filter(todo => {
          return todo.id !== id
        });
      },
      // 勾选或者取消勾选全部
      checkAllTodo(done){
        this.todos.forEach(todo => {
          todo.done = done
        });
      },
      // 删除所有已经完成的todo
      clearAllTodo(){
        this.todos = this.todos.filter(todo => {
          return !todo.done
        });
      }
    },
    mounted() {
      this.$bus.$on("checkTodo",this.checkTodo)
      // this.$bus.$on("deteleTodo",this.deteleTodo)
      this.pId = PubSub.subscribe('deteleTodo',this.deteleTodo)
    },
    beforeDestroy() {
      this.$bus.$off(['checkTodo'])
      PubSub.unsubscribe(this.pId)
    },
  }
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
